import { reqGetCode, reqUserInfo, reqUserLogin, reqUserLogout, reqUserRegister } from "@/api"
import {getToken, removeToken, setToken} from "@/utils/token"
const state={
  code:'',
  token:getToken(),
  userInfo:{}
}
const mutations={
  GETCODE(state,code){
    state.code=code
  },
  USERLOGIN(state,token){
    state.token=token
  },
  GETUSERINFO(state,userInfo){
    state.userInfo=userInfo
  },
  USERLOGOUT(state){
    //清除相关仓库
    state.token=''
    state.userInfo={}
    //清除本地存储
    removeToken()
  }
}
const actions={
  //获取验证码
  async getCode({ commit }, phone) {
    //获取验证码的这个接口：把验证码返回，但是正常情况，后台把验证码发到用户手机上【省钱】
    let result = await reqGetCode(phone);
    if (result.code == 200) {
      commit("GETCODE", result.data);
      return "ok";
    } else {
      return Promise.reject(new Error("faile"));
    }
  },
  //用户注册
  async userRegister({commit},user){
    let result=await reqUserRegister(user)
    if(result.code==200){
      return 'ok'
    }else{
      return Promise.reject(new Error('fail'))
    }
  },
  //用户登录
  async userLogin({commit},data){
    //服务器下发token，用户唯一标识符(uuid)
    //将来经常通过带token找服务器要用户信息进行展示
    let result =await reqUserLogin(data)
    if(result.code==200){  
      commit("USERLOGIN",result.data.token)  
      //持久化存储token
      setToken(result.data.token); 
      return 'ok'
    }else{
      return Promise.reject(new Error('fail'))
    }
  },
  //获取用户信息
  async getUserInfo({commit}){
    let result =await reqUserInfo()
    if(result.code==200){
      commit('GETUSERINFO',result.data)
    }
  },
  //退出登录
  async userLogout({commit}){
    let result =await reqUserLogout()
    if(result.code==200){
      commit('USERLOGOUT')
      return 'ok'
    }else{
      return Promise(new Error('fail'))
    }
  }
}
const getters={}
export default{
  state,
  mutations,
  actions,
  getters
}